package com.guli.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.base.exception.GuliException;
import com.guli.edu.entity.Subject;
import com.guli.edu.entity.excel.SubjectExcelData;
import com.guli.edu.entity.vo.OneSubject;
import com.guli.edu.entity.vo.TwoSubject;
import com.guli.edu.listener.SubjectExcelListener;
import com.guli.edu.mapper.SubjectMapper;
import com.guli.edu.service.SubjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author ZhaoZhenyu
 * @since 2022-09-25
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    // 读取Excel数据到数据库
    // easyExcel是利用监听器一行一行的读
    @Override
    public void addSubjectByExcel(MultipartFile file, SubjectService subjectService) {
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectExcelData.class, new SubjectExcelListener(subjectService)).sheet().doRead();

        } catch (IOException e) {
            e.printStackTrace();
            throw new GuliException(20002, "添加课程失败");
        }

    }

    @Override
    public List<OneSubject> getSubjectList() {
        // 得到全部一级分类 pid为0的
        List<Subject> allOneSubjectList= baseMapper.selectList(new QueryWrapper<Subject>().eq("parent_id", "0"));
        // 得到全部二级分类 不为0的
        List<Subject> allTwoSubjectList= baseMapper.selectList(new QueryWrapper<Subject>().ne("parent_id", "0"));
        // 填充一级分类 包括二级分类集合 遍历所有集合取出每一个一级并对其填充
        ArrayList<OneSubject> oneSubjectList = new ArrayList<>();
        for (Subject subject1 : allOneSubjectList) {
            // 自定义实体接收原实体类，只取两个字段
            OneSubject oneSubject = new OneSubject();
            // 使用spring工具类转换
            BeanUtils.copyProperties(subject1, oneSubject);
            // 二级分类的集合存放每一个一级对应二级集合
            ArrayList<TwoSubject> twoSubjectList = new ArrayList<>();
            for (Subject subject2 : allTwoSubjectList) {
                // 一级id与二级parent_id一一对应的放一块
                if (subject1.getId().equals(subject2.getParentId())){
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(subject2, twoSubject);
                    twoSubjectList.add(twoSubject);
                }
            }
            oneSubject.setChildren(twoSubjectList);
            // 将每一个带有二级集合的一级类放入集合
            oneSubjectList.add(oneSubject);
        }
        return oneSubjectList;
    }
}
